package com.fivestar.pmanager.web.auth;

import com.fivestar.pmanager.core.util.CodeHelper;
import com.fivestar.pmanager.model.FsUserBean;
import com.fivestar.pmanager.model.SysRoleBean;
import com.fivestar.pmanager.service.FsUserService;
import com.fivestar.pmanager.service.SysRoleUserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

public class MyUserDetailServiceImpl implements UserDetailsService
{
    private static final Logger logger = LoggerFactory.getLogger(MyUserDetailServiceImpl.class);
    private FsUserService fsUserService;
    private SysRoleUserService sysRoleUserService;

    @Override
    public UserDetails loadUserByUsername(String s)
            throws UsernameNotFoundException
    {
        logger.debug("loginId:" + s);
        FsUserBean userBean = fsUserService.loadByNameOrPhone(s);
        if (userBean == null)
        {
            throw new UsernameNotFoundException(s);
        }
        return new MyUserDetails(s, userBean.getPassword(), obtionGrantedAuthorities(userBean), true, true, true, true, userBean);
    }


    //取得用户的权限
    private List<GrantedAuthority> obtionGrantedAuthorities(FsUserBean user)
    {

        List<GrantedAuthority> authSet = null;
        List<SysRoleBean> roles = sysRoleUserService.findUserRole(user.getRowId());
        if(CodeHelper.isNotNull(roles))
        {
            authSet = new ArrayList<>(roles.size());
            for(SysRoleBean role : roles)
            {
                authSet.add(new SimpleGrantedAuthority(role.getCode()));
            }
        }
        
        // 新增公共权限
        authSet.add(new SimpleGrantedAuthority("COMM"));
        return authSet;
    }


	public FsUserService getFsUserService() {
		return fsUserService;
	}


	public void setFsUserService(FsUserService fsUserService) {
		this.fsUserService = fsUserService;
	}


	public SysRoleUserService getSysRoleUserService() {
		return sysRoleUserService;
	}


	public void setSysRoleUserService(SysRoleUserService sysRoleUserService) {
		this.sysRoleUserService = sysRoleUserService;
	}
    

}
